<template>
<div class="login">
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="ruleForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="ruleForm.password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >登录</el-button
      >
      <el-button @click="toReg">注册</el-button>
    </el-form-item>
  </el-form>
</div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import {ElMessage} from 'element-plus';
import { get, post } from '../request/api';
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from "vue-router"
const router = useRouter()
    
const formSize = ref('')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  username: '',
  password: '',
})

const rules = reactive<FormRules>({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      min: 5,
      max: 12,
      message: '密码长度为5-12位',
      trigger: 'blur',
    },
  ],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      console.log('submit!')
      post('/login',ruleForm).then(res=>{
        console.log(res);
        if(res.code==200){
          ElMessage.success('登录成功')
          router.push({
            path: '/home',
          })
        }else{
          ElMessage.error(res.message)
        }
      }).catch(err=>{
        ElMessage.error('登录失败')
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const toReg =async () => {
  post('/reg',ruleForm).then(res=>{
    console.log(res);
    if(res.code==200){
      ElMessage.success('注册成功！')
    }else{
      ElMessage.error(res.message)
    }
  }).catch(err=>{
    ElMessage.error('注册失败')
  })
}
</script>
<style lang="less" scoped>
.login{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .demo-ruleForm{
    width: 400px;
    height: 300px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-right: 50px;
    border: 1px solid #c2c2c2;
  }
}
</style>
